package com.ysd.lis.service.iqc.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.iqc.QcMaterialItemResultGdb;
import com.ysd.lis.entity.lab.LabInstrSetup;
import com.ysd.lis.entity.lab.LabItemDict;
import com.ysd.lis.entity.qc.*;
import com.ysd.lis.mapper.iqc.QcMaterialItemResultGdbMapper;
import com.ysd.lis.mapper.lab.LabInstrSetupMapper;
import com.ysd.lis.mapper.lab.LabItemDictMapper;
import com.ysd.lis.mapper.qc.QcInstrItemMapper;
import com.ysd.lis.mapper.qc.QcMaterialItemMapper;
import com.ysd.lis.mapper.qc.QcMaterialItemTargetMapper;
import com.ysd.lis.mapper.qc.QcMaterialMapper;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.service.iqc.QcMaterialItemResultGdbService;
import com.ysd.lis.service.qc.QcMaterialItemResultService;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2024-01-08
 */
@Service
@Slf4j
public class QcMaterialItemResultGdbServiceImpl extends ServiceImpl<QcMaterialItemResultGdbMapper, QcMaterialItemResultGdb> implements QcMaterialItemResultGdbService {
    @Autowired
    LabInstrSetupMapper labInstrSetupMapper;
    @Autowired
    QcMaterialItemResultGdbMapper qcMaterialItemResultGdbMapper;
    @Autowired
    QcMaterialMapper qcMaterialMapper;
    @Autowired
    LabItemDictMapper labItemDictMapper;
    @Autowired
    QcInstrItemMapper qcInstrItemMapper;
    @Autowired
    QcMaterialItemMapper qcMaterialItemMapper;
    @Autowired
    QcMaterialItemTargetMapper qcMaterialItemTargetMapper;
    @Autowired
    QcMaterialItemResultService qcMaterialItemResultService;

    @Override
    public Result transQcMaterialItemResult(CommonPageDto pageParam) {
        Page<QcMaterialItemResultGdb> page = new Page<>();
        page.setCurrent(1);
        page.setSize(500);
        LambdaQueryWrapper<QcMaterialItemResultGdb> queryWrapperGdb = new LambdaQueryWrapper<>();
        queryWrapperGdb.eq(QcMaterialItemResultGdb::getIsSync,false)
                .and(p->p.eq(QcMaterialItemResultGdb::getNoSync,"").or().isNull(QcMaterialItemResultGdb::getNoSync))
                .orderByAsc(QcMaterialItemResultGdb::getQcDate);

        Page<QcMaterialItemResultGdb> qcMaterialItemResultGdbPage = qcMaterialItemResultGdbMapper.selectPage(page, queryWrapperGdb);
        List<QcMaterialItemResultGdb> resultGdbList = qcMaterialItemResultGdbPage.getRecords();

        if(ToolsUtils.isNotEmpty(resultGdbList)){

            List<String> instrCodeList = resultGdbList.stream().map(QcMaterialItemResultGdb::getInstrCode).distinct().collect(Collectors.toList());
            //根据code查询仪器
            MPJLambdaWrapper<LabInstrSetup> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.eq(LabInstrSetup::getDelFlag,0)
                    .in(LabInstrSetup::getInstrCode,instrCodeList);
            List<LabInstrSetup> instrSetupList = labInstrSetupMapper.selectList(queryWrapper);

            List<QcMaterialItemResult> addList = new ArrayList<>();
            for(QcMaterialItemResultGdb resultGdb : resultGdbList){

                //找仪器
                String instrCode = resultGdb.getInstrCode();
                List<LabInstrSetup> collect = instrSetupList.stream().filter(a -> a.getInstrCode().equals(instrCode)).collect(Collectors.toList());
                LabInstrSetup labInstrSetup = collect.get(0);

                //仪器，批号，水平 确定一条质控物
                LambdaQueryWrapper<QcMaterial> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(QcMaterial::getInstrId,labInstrSetup.getId())
                        .eq(QcMaterial::getBatchNum,resultGdb.getBatchNumber())
                        .eq(QcMaterial::getHorizontal,resultGdb.getHorizontal())
                        .eq(QcMaterial::getDelFlag,0);
                List<QcMaterial> qcMaterials = qcMaterialMapper.selectList(queryWrapper2);
                if(ToolsUtils.isNotEmpty(qcMaterials)){
                    //当前数据对应得质控物
                    QcMaterial qcMaterial = qcMaterials.get(0);
                    //根据项目code和仪器得报告单元查出报告项目
                    String rptGroup = labInstrSetup.getRptGroup();
                    String itemNo = resultGdb.getItemNo();
                    LambdaQueryWrapper<LabItemDict> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(LabItemDict::getDelFlag,0)
                            .eq(LabItemDict::getRptGroup,rptGroup)
                            .eq(LabItemDict::getItemNo,itemNo);
                    List<LabItemDict> labItemDicts = labItemDictMapper.selectList(queryWrapper1);
                    if(ToolsUtils.isNotEmpty(labItemDicts)){
                        LabItemDict itemDict = labItemDicts.get(0);
                        //根据报告项目id，仪器ID查出仪器质控项目
                        LambdaQueryWrapper<QcInstrItem> queryWrapper3 = new LambdaQueryWrapper<>();
                        queryWrapper3.eq(QcInstrItem::getDelFlag,0)
                                .eq(QcInstrItem::getInstrId,labInstrSetup.getId())
                                .eq(QcInstrItem::getItemDictId,itemDict.getId());
                        List<QcInstrItem> qcInstrItems = qcInstrItemMapper.selectList(queryWrapper3);
                        if(ToolsUtils.isNotEmpty(qcInstrItems)){
                            QcInstrItem qcInstrItem = qcInstrItems.get(0);
                            //查看是否有此质控物项目
                            LambdaQueryWrapper<QcMaterialItem> queryWrapper4 = new LambdaQueryWrapper<>();
                            queryWrapper4.eq(QcMaterialItem::getDelFlag,0)
                                    .eq(QcMaterialItem::getMaterialId,qcMaterial.getId())
                                    .eq(QcMaterialItem::getInstrId,labInstrSetup.getId())
                                    .eq(QcMaterialItem::getQcItemId,qcInstrItem.getId());
                            List<QcMaterialItem> qcMaterialItems = qcMaterialItemMapper.selectList(queryWrapper4);
                            if(ToolsUtils.isNotEmpty(qcMaterialItems)){
                                QcMaterialItem qcMaterialItem = qcMaterialItems.get(0);

                                Timestamp qcDate = resultGdb.getQcDate();
                                Date date = new Date(qcDate.getTime());
                                //根据质控物，质控物细项，质控日期，质控次数查看是否有此结果
                                LambdaQueryWrapper<QcMaterialItemResult> queryWrapper6 = new LambdaQueryWrapper<>();
                                queryWrapper6.eq(QcMaterialItemResult::getDelFlag,0)
                                        .eq(QcMaterialItemResult::getMaterialId,qcMaterial.getId())
                                        .eq(QcMaterialItemResult::getMaterialItemId,qcMaterialItem.getId())
                                        .eq(QcMaterialItemResult::getQcSequence,resultGdb.getQcSequence())
                                        .ge(QcMaterialItemResult::getQcDate, DateUtil.beginOfDay(date).toTimestamp())
                                        .le(QcMaterialItemResult::getQcDate, DateUtil.endOfDay(date).toTimestamp());
                                Integer count = qcMaterialItemResultService.count(queryWrapper6);
                                if(count<=0){
                                    //查看是否有靶值
                                    LambdaQueryWrapper<QcMaterialItemTarget> queryWrapper5 = new LambdaQueryWrapper<>();
                                    queryWrapper5.eq(QcMaterialItemTarget::getMaterialItemId,qcMaterialItem.getId())
                                            .eq(QcMaterialItemTarget::getDelFlag,0);
                                    List<QcMaterialItemTarget> itemTargetList = qcMaterialItemTargetMapper.selectList(queryWrapper5);

                                    QcMaterialItemResult result = new QcMaterialItemResult();
                                    result.setMaterialId(qcMaterial.getId());
                                    result.setMaterialItemId(qcMaterialItem.getId());
                                    result.setQcItemId(qcInstrItem.getId());
                                    result.setInstrId(labInstrSetup.getId());
                                    result.setItemDictId(itemDict.getId());
                                    if(ToolsUtils.isNotEmpty(itemTargetList)){
                                        result.setMaterialTargetId(itemTargetList.get(0).getId());
                                    }
                                    result.setBatchNum(resultGdb.getBatchNumber());
                                    result.setHorizontal(resultGdb.getHorizontal());
                                    result.setQcNo(qcMaterial.getQcNo());
                                    result.setQcDate(resultGdb.getQcDate());
                                    result.setQcSequence(resultGdb.getQcSequence());
                                    result.setNumResult(resultGdb.getNumResult());
                                    result.setResult(resultGdb.getResult());
                                    result.setMean(resultGdb.getMean());
                                    result.setSd(resultGdb.getSd());
                                    result.setZ(resultGdb.getZ());
                                    result.setIsAlarm(resultGdb.getIsAlarm());
                                    result.setAlarmRules(resultGdb.getAlarmRules());
                                    result.setIsOutControl(resultGdb.getIsOutControl());
                                    result.setOutControlRules(resultGdb.getOutControlRules());
                                    result.setIsOutControlHandled(resultGdb.getIsOutControlHandled());
                                    result.setIsBestInDay(resultGdb.getIsBestInDay());
                                    result.setIntResultId(resultGdb.getId());
                                    result.setOrgId(qcMaterial.getOrgId());
                                    addList.add(result);
                                    resultGdb.setIsSync(true);
                                    resultGdb.setNoSync("同步成功");
                                }else {
                                    resultGdb.setNoSync("数据存在");
                                }
                            }
                        }
                    }
                }
            }

            boolean b1 = qcMaterialItemResultService.saveBatch(addList);
            List<QcMaterialItemResultGdb> collect = resultGdbList.stream().filter(a -> a.getIsSync()||ToolsUtils.isNotEmpty(a.getNoSync())).collect(Collectors.toList());
            if(ToolsUtils.isNotEmpty(collect)){
                boolean b = this.updateBatchById(collect);
            }

        }


        return null;
    }
}
